import os
import unittest
from unittest.mock import patch, MagicMock
from utils import (
    exception_handler,
    FunctionExecutionError,
)  # 假设你的装饰器在 your_module.py 文件中


# 模拟 Streamlit 的 st.error 方法
class MockSt:
    @staticmethod
    def error(message, icon=None):
        print(f"Streamlit error: {message}")


# 使用模拟的 Streamlit 模块
st = MockSt()


# 被测试的函数
@exception_handler
def test_function(x, y):
    if not isinstance(x, int) or not isinstance(y, int):
        raise TypeError("Both arguments must be integers.")
    return x + y


@exception_handler
def another_test_function():
    raise ValueError("This is a value error.")


class TestExceptionHandler(unittest.TestCase):
    def setUp(self):
        # 清空日志文件
        with open("app.log", "w"):
            pass

    def tearDown(self):
        # 删除日志文件
        if os.path.exists("app.log"):
            os.remove("app.log")

    def test_type_error(self):
        with self.assertRaises(FunctionExecutionError):
            test_function(1, "2")

        # 检查日志文件
        with open("app.log", "r") as log_file:
            log_content = log_file.read()
            self.assertIn(
                "A TypeError occurred in function 'test_function': Both arguments must be integers.",
                log_content,
            )

    def test_value_error(self):
        with self.assertRaises(FunctionExecutionError):
            another_test_function()

        # 检查日志文件
        with open("app.log", "r") as log_file:
            log_content = log_file.read()
            self.assertIn(
                "A ValueError occurred in function 'another_test_function': This is a value error.",
                log_content,
            )


if __name__ == "__main__":
    unittest.main()
